<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 200px;
            height: 200px;
            background-color: aquamarine;

            position: absolute;
            left: 50px;
            top: 50px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>
<script>
    // 需求: 鼠标拖拽盒子移动
    // (1) onmousedown 先按下 => 记录按下的位置
    // (2) onmousemove 再移动 => 盒子跟随鼠标相对于按下的位置移动
    // (3) onmouseup  再松开 => 盒子不在跟随鼠标移动


    var box = document.querySelector(".box");

    // 按下时 => 记录按下的位置
    box.onmousedown = function (e) {
        e = e || window.event;

        var posX = e.offsetX;
        var posY = e.offsetY;
        console.log(posX, posY);


        // 先按下,再移动
        document.onmousemove = function (e) {
            e = e || window.event;
            console.log("鼠标在移动");

            var x = e.pageX - posX;
            var y = e.pageY - posY;

            box.style.left = x+"px";
            box.style.top = y+"px";
            
        }

        // 在文档任意位置松开
        document.onmouseup = function(){
            document.onmousemove = null;
        }
    }





</script>

</html>